package com.partyjoin.project.module.proposer.controller;




import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import ch.qos.logback.core.db.dialect.DBUtil;
import javafx.scene.input.DataFormat;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.deepoove.poi.XWPFTemplate;
import com.partyjoin.common.constant.Constants;
import com.partyjoin.common.utils.DateUtils;
import com.partyjoin.common.utils.ServletUtils;
import com.partyjoin.common.utils.security.ShiroUtils;
import com.partyjoin.framework.aspectj.lang.annotation.Log;
import com.partyjoin.framework.aspectj.lang.constant.BusinessType;
import com.partyjoin.framework.web.controller.BaseController;
import com.partyjoin.framework.web.domain.AjaxResult;
import com.partyjoin.framework.web.page.TableDataInfo;
import com.partyjoin.project.module.proposer.domain.Proposer;
import com.partyjoin.project.module.proposer.service.IProposerService;
import com.partyjoin.project.system.user.domain.User;
import com.partyjoin.project.system.user.service.IUserService;

/**
 * 申请人材料 信息操作处理
 * 
 * @author 莫东林
 * @date 2018-07-19
 */
@Controller
@RequestMapping("/module/proposer")
public class ProposerController extends BaseController
{
    private String prefix = "module/proposer";
	
	@Autowired
	private IProposerService proposerService;
	@Autowired
	private IUserService userService;
	@Autowired
	private DocumentConverter documentConverter;
	
	
	@RequiresPermissions("module:proposer:view")
	@GetMapping()
	public String proposer()
	{
	    return prefix + "/proposer";
	}
	
	/**
	 * 保存申请人的各种材料
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/materials/upload")
	@ResponseBody
	public AjaxResult materialsUpload(@RequestParam(value = "type") String type,
			MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        String fileType = Constants.getFilePath(type);//根据文件类型获取指定文件上传路径
        boolean success = upload(user, file, fileType);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer = updateProposer(proposer, user, users, type, file.getOriginalFilename());
            proposerService.updateProposer(proposer);
        } else{
        	return error("上传失败");
        }
		return success("上传成功");
	}
	
	/**
	 * 根据文件类型设置更新proposer
	 * @param proposer 材料对象
	 * @param user 申请人
	 * @param users	操作者
	 * @param type 文件类型
	 * @param fileName	文件名称
	 * @return
	 */
	public Proposer updateProposer(Proposer proposer, User user, User users, String type, String fileName){
		switch(type){
		case "partyApplication":
			proposer.setPartyApplication("/"+user.getUserId()+"/"+fileName);
			proposer.setApplicationTime(DateUtils.getNowDate());
			break;
		case "partyMemcon":
			proposer.setPartyMemcon("/"+user.getUserId()+"/"+fileName);
			proposer.setMemconTime(DateUtils.getNowDate());
			break;
		case "partymemberRecommend":
			proposer.setPartymemberRecommend("/"+user.getUserId()+"/"+fileName);
			break;
		case "groupRecommend":
			proposer.setGroupRecommend("/"+user.getUserId()+"/"+fileName);
			break;
		case "activistRecords":
			proposer.setActivistRecords("/"+user.getUserId()+"/"+fileName);
			break;
		case "activistRecordsReport":
			proposer.setActivistRecordsReport("/"+user.getUserId()+"/"+fileName);
			break;
		case "activistCultivate":
			proposer.setActivistCultivate("/"+user.getUserId()+"/"+fileName);
			break;
		case "developmentRecords":
			proposer.setDevelopmentRecords("/"+user.getUserId()+"/"+fileName);
			break;
		case "developmentPublicity":
			proposer.setDevelopmentPublicity("/"+user.getUserId()+"/"+fileName);
			break;
		case "developmentRecordsReport":
			proposer.setDevelopmentRecordsReport("/"+user.getUserId()+"/"+fileName);
			break;
		case "developmentCultivate":
			proposer.setDevelopmentCultivate("/"+user.getUserId()+"/"+fileName);
			break;
		case "reportFirst":
			proposer.setReportFirst("/"+user.getUserId()+"/"+fileName);
			proposer.setReportLastTime(DateUtils.getNowDate());
			break;
		case "reportSecond":
			proposer.setReportSecond("/"+user.getUserId()+"/"+fileName);
			proposer.setReportLastTime(DateUtils.getNowDate());
			break;
		case "reportThird":
			proposer.setReportThird("/"+user.getUserId()+"/"+fileName);
			proposer.setReportLastTime(DateUtils.getNowDate());
			break;
		case "reportFourth":
			proposer.setReportFourth("/"+user.getUserId()+"/"+fileName);
			proposer.setReportLastTime(DateUtils.getNowDate());
			break;
		case "reportFifth":
			proposer.setReportFifth("/"+user.getUserId()+"/"+fileName);
			proposer.setReportLastTime(DateUtils.getNowDate());
			break;
		case "reportSixth":
			proposer.setReportSixth("/"+user.getUserId()+"/"+fileName);
			proposer.setReportLastTime(DateUtils.getNowDate());
			break;
		case "reportSeventh":
			proposer.setReportSeventh("/"+user.getUserId()+"/"+fileName);
			proposer.setReportLastTime(DateUtils.getNowDate());
			break;
		case "reportEighth":
			proposer.setReportEighth("/"+user.getUserId()+"/"+fileName);
			proposer.setReportLastTime(DateUtils.getNowDate());
			break;
		case "partyApplicaiton":
			proposer.setPartyApplicaiton("/"+user.getUserId()+"/"+fileName);
			break;
		case "officialApplication":
			proposer.setOfficialApplication("/"+user.getUserId()+"/"+fileName);
			break;
		case "memoir":
			proposer.setMemoir("/"+user.getUserId()+"/"+fileName);
			break;
		case "developmentInvestigate":
			proposer.setDevelopmentInvestigate("/"+user.getUserId()+"/"+fileName);
			break;
		case "prepareInvestigate":
			proposer.setPrepareInvestigate("/"+user.getUserId()+"/"+fileName);
			break;
		case "prepareToofficialPublicity":
			proposer.setPrepareToofficialPublicity("/"+user.getUserId()+"/"+fileName);
			break;
		case "developmentRemaineRequest":
			proposer.setDevelopmentRemaineRequest("/"+user.getUserId()+"/"+fileName);
			break;
		case "developmentRemaineVerdict":
			proposer.setDevelopmentRemaineVerdict("/"+user.getUserId()+"/"+fileName);
			break;
		case "prepareRemaineRequest":
			proposer.setPrepareRemaineRequest("/"+user.getUserId()+"/"+fileName);
			break;
		case "prepareAcceptReport":
			proposer.setPrepareAcceptReport("/"+user.getUserId()+"/"+fileName);
			break;
		case "prepareToOfficialRequest":
			proposer.setPrepareToofficialRequest("/"+user.getUserId()+"/"+fileName);
			break;
		}
        proposer.setUpdateBy(users.getUserName());
        proposer.setUpdateTime(new Date());
        return proposer;
	}
	
	/**
	 * 打开成员提交材料页面
	 */
	@RequiresPermissions("module:proposer:view")
	@GetMapping("/materials/submit")
	public String materialsSubmit(Model model){
		//取登录用户
		User user = userService.selectProposer(ShiroUtils.getUserId());
		model.addAttribute("user", user);
		return prefix + "/materialsSubmit";
	}
	
	/**
	 * 党委管理员打开成员材料页面
	 * @param userId
	 * @param model
	 * @return
	 */
	@RequiresPermissions("module:proposer:view")
	@GetMapping("/getMaterials/{userId}")
	public String getMaterials(@PathVariable Long userId, Model model){
		User user = userService.selectProposer(userId);
		model.addAttribute("user", user);
		return prefix + "/materials";
	}

	/**
	 * 打开入党申请人详情
	 */
	@RequiresPermissions("module:proposer:view")
	@GetMapping("applicationDetails")
	public String applicationDetails(User user, Model model){
		user = userService.selectProposer(user.getUserId());
		model.addAttribute("user", user);
		return prefix + "/applicationDetails";
	}
	
	/**
	 * 预览文件
	 * @param userId
	 * @param type
	 * @param fileName
	 * @param response
	 * @throws IOException 
	 */
	@RequiresPermissions("module:proposer:view")
	@GetMapping("/review")
	public void  review(@RequestParam(name = "userId", required = true) Long userId,
			@RequestParam(name = "type", required = true) String type, 
			@RequestParam(name = "fileName", required = true) String fileName,
			HttpServletResponse response) throws IOException{
		String path = "";//服务器环境
		String filePath = "";//文件绝对路径
		//预览模板
		if(fileName == null || fileName.equals("")){
			System.out.println("预览模板");
			filePath = Constants.getFilePaths(type);
			fileName = type+".docx";
		}else{
			//非模板
			System.out.println("非模板");
			path = Constants.getFilePath(type);
			filePath = path +fileName;
		}
		System.out.println("预览文件位置："+filePath);
        /*将文件写入输出流,显示在界面上,实现预览效果*/
		review(fileName, filePath, response);
		
    }
	
	
	
	/**
	 * 渲染word模板
	 */
	public XWPFTemplate getTemplate(String filePath, String type, User user){

		XWPFTemplate template = null;
		Date date = DateUtils.getNowDate();
		DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
		String s = dateFormat.format(date);
		DateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");


		switch(type){
		case "partyApplication":
			template = XWPFTemplate.compile(filePath).render(new HashMap<String, Object>(){{
		        put("userName", user.getUserName());
		        put("day",s);
			}});
			break;
		case "partyMemcon":
			template = XWPFTemplate.compile(filePath).render(new HashMap<String, Object>(){{
				put("userName", user.getUserName());
				put("department", user.getDept().getDeptName());
				put("memconDate",s);

				String nation = Constants.getNationName(user.getNation());
				put("nation",nation);

				String educationLevel = Constants.getEducationLevel(user.getEducationLevel());
				put("educationLevel",educationLevel);

				try {
					String birthDay = user.getBirthday();
					Date d = df.parse(birthDay);
					birthDay = dateFormat.format(d);
					put("birthDay",birthDay);
				}catch(ParseException e){
					e.printStackTrace();
				}

				Date d1 = user.getProposer().getApplicationTime();
				String applicationTime = dateFormat.format(d1);
				put("applicationTime",applicationTime);


			}});
			break;
		case "partymemberRecommend":
			template = XWPFTemplate.compile(filePath).render(new HashMap<String, Object>(){{
				put("userName", user.getUserName());

				String sex = user.getSex();
				if(sex.equals("0")){
					put("sex", "男");
				}else if(sex.equals("1")){
					put("sex", "女");
				}else{
					put("sex", "其它");
				}

				String nation = Constants.getNationName(user.getNation());
				put("nation",nation);

				try {
					String birthDay = user.getBirthday();
					Date d = df.parse(birthDay);
					birthDay = dateFormat.format(d);
					put("birthDay",birthDay);
				}catch(ParseException e){
					e.printStackTrace();
				}

				String educationLevel = Constants.getEducationLevel(user.getEducationLevel());
				put("educationLevel",educationLevel);

				Date d1 = user.getProposer().getApplicationTime();
				String applicationTime = dateFormat.format(d1);
				put("applicationTime",applicationTime);

			}});
			break;
		case "groupRecommend":
			template = XWPFTemplate.compile(filePath).render(new HashMap<String, Object>(){{

				put("userName", user.getUserName());

				String sex = user.getSex();
				if(sex.equals("0")){
					put("sex", "男");
				}else if(sex.equals("1")){
					put("sex", "女");
				}else{
					put("sex", "其它");
				}

				String nation = Constants.getNationName(user.getNation());
				put("nation",nation);

				try {
					String birthDay = user.getBirthday();
					Date d = df.parse(birthDay);
					birthDay = dateFormat.format(d);
					put("birthDay",birthDay);
				}catch(ParseException e){
					e.printStackTrace();
				}

				String educationLevel = Constants.getEducationLevel(user.getEducationLevel());
				put("educationLevel",educationLevel);

				Date d1 = user.getProposer().getApplicationTime();
				String applicationTime = dateFormat.format(d1);
				put("applicationTime",applicationTime);

			}});
			
			break;
		case "activistRecords":
			template = XWPFTemplate.compile(filePath).render(new HashMap<String, Object>(){{
				put("userName", user.getUserName());

				String sex = user.getSex();
				if(sex.equals("0")){
					put("sex", "男");
				}else if(sex.equals("1")){
					put("sex", "女");
				}else{
					put("sex", "其它");
				}

				String nation = Constants.getNationName(user.getNation());
				put("nation",nation);

				try {
					String birthDay = user.getBirthday();
					Date d = df.parse(birthDay);
					birthDay = dateFormat.format(d);
					put("birthDay",birthDay);
				}catch(ParseException e){
					e.printStackTrace();
				}

				String educationLevel = Constants.getEducationLevel(user.getEducationLevel());
				put("educationLevel",educationLevel);

				Date d1 = user.getProposer().getApplicationTime();
				String applicationTime = dateFormat.format(d1);
				put("applicationTime",applicationTime);
				put("nowDay",s);
			}});


			break;
		case "activistRecordsReport":
			template = XWPFTemplate.compile(filePath).render(new HashMap<String, Object>(){{
				put("userName", user.getUserName());

				String sex = user.getSex();
				if(sex.equals("0")){
					put("sex", "男");
				}else if(sex.equals("1")){
					put("sex", "女");
				}else{
					put("sex", "其它");
				}

				String nation = Constants.getNationName(user.getNation());
				put("nation",nation);

				try {
					String birthDay = user.getBirthday();
					Date d = df.parse(birthDay);
					birthDay = dateFormat.format(d);
					put("birthDay",birthDay);
				}catch(ParseException e){
					e.printStackTrace();
				}

				String educationLevel = Constants.getEducationLevel(user.getEducationLevel());
				put("educationLevel",educationLevel);

				Date d1 = user.getProposer().getApplicationTime();
				String applicationTime = dateFormat.format(d1);
				put("applicationTime",applicationTime);
				put("nowDay",s);
			}});
			break;
		case "activistCultivate":
			template = XWPFTemplate.compile(filePath).render(new HashMap<String, Object>(){{
				put("userName", user.getUserName());

				String sex = user.getSex();
				if(sex.equals("0")){
					put("sex", "男");
				}else if(sex.equals("1")){
					put("sex", "女");
				}else{
					put("sex", "其它");
				}

				String nation = Constants.getNationName(user.getNation());
				put("nation",nation);

				try {
					String birthDay = user.getBirthday();
					Date d = df.parse(birthDay);
					birthDay = dateFormat.format(d);
					put("birthDay",birthDay);
				}catch(ParseException e){
					e.printStackTrace();
				}

				String educationLevel = Constants.getEducationLevel(user.getEducationLevel());
				put("educationLevel",educationLevel);

				Date d1 = user.getProposer().getApplicationTime();
				String applicationTime = dateFormat.format(d1);
				put("applicationTime",applicationTime);
				put("nowDay",s);
			}});
			break;
		}
		return template;
	}

	/**
	 * 下载各种资料
	 * @param userId
	 * @param type 资料类型
	 * @param fileName 相对路径+文件名
	 * @param response 响应对象
	 * @throws IOException 
	 */
	@SuppressWarnings("deprecation")
	@RequiresPermissions("module:proposer:view")
	@GetMapping("/download")
	public void download(@RequestParam(name = "userId", required = true) Long userId,
			@RequestParam(name = "type", required = true) String type, 
			@RequestParam(name = "fileName", required = true) String fileName,
			HttpServletResponse response) throws IOException{
			User user = userService.selectProposer(userId);
			String path = "";//服务器环境
			String filePath = "";//文件绝对路径
			//下载模板
			if(fileName == null || fileName.equals("")){
				//获取工程路径
				filePath = Constants.getFilePaths(type);
//				System.out.println(filePath);
				//核心API采用了极简设计，只需要一行代码
/*				XWPFTemplate template = getTemplate(filePath, type, user);
				OutputStream os = response.getOutputStream();
                response.reset();
                response.setHeader("Content-disposition", "attachment; filename=\""+ URLEncoder.encode(user.getUserName() + "-" + Constants.getFileName(type), "UTF-8"));
                response.setContentType("APPLICATION/OCTET-STREAM");
				System.out.println(" "+filePath+" "+type+" "+user);
                System.out.println("template: "+template);
                template.write(os);
                template.close();
                os.flush();   
                os.close();   
				return;*/
			}else{
				//不是模板
				path = Constants.getFilePath(type);
				filePath = path + fileName;
			}
			fileName = Constants.getFileName(type);
//			System.out.println(filePath);
			response.setHeader("content-type", "application/octet-stream");
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(user.getUserName() + "-" + fileName + ".docx"));
	          byte[] buff = new byte[1024];
	          BufferedInputStream bis = null;
	          OutputStream os = null;
	          try {
	            os = response.getOutputStream();
	            bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
	            int i = bis.read(buff);
	            while (i != -1) {
	              os.write(buff, 0, buff.length);
	              os.flush();
	              i = bis.read(buff);
	            }
	          } catch (IOException e) {
	            e.printStackTrace();
	          } finally {
	            if (bis != null) {
	              try {
	                bis.close();
	              } catch (IOException e) {
	                e.printStackTrace();
	              }
	            }
	          }
	}
	

	/**
	 * 打开申请入党管理界面
	 */
	@RequiresPermissions("module:proposer:view")
	@GetMapping("/partyJoin")
	public String partyJoin(){
		return prefix + "/partyJoin";
	}
	
	/**
	 * 获取申请入党管理数据列表
	 * @param user
	 * @return
	 */
    @RequiresPermissions("module:proposer:list")
    @PostMapping("/partyJoin/list")
    @ResponseBody
    public TableDataInfo memberList(User user){
    	startPage();
    	user.setDeptId(ShiroUtils.getUserDeptId());
    	List<User> list = userService.selectPartyJoin(user);
    	return getDataTable(list);
    }
	
	/**
	 * 打开递交入党申请书界面
	 */
	@RequiresPermissions("module:proposer:add")
	@GetMapping("/partyApplicationAdd")
	public String partyApplicationAdd(){
		return prefix + "/partyApplicationAdd";
	}
	
	/**
	 * 保存入党申请书
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/partyApplication/save")
	@ResponseBody
	public AjaxResult partyApplicationSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.PARTY_APPLICATION);
        if(success){
            Proposer proposer = proposerService.selectProposerById(users.getUserId());
            proposer.setPartyApplication("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setApplicationTime(new Date());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
        } else{
        	return error("上传失败");
        }
		return success("上传成功");
	}
	
	/**
	 * 保存谈话记录
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/partyMemcon/save")
	@ResponseBody
	public AjaxResult partyMemconSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
		User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.PARTY_MEMCON);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setPartyMemcon("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setMemconTime(DateUtils.getNowDate());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	

	/**
	 * 保存党员推荐入党积极分子登记表
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/partyMemberRecommend/save")
	@ResponseBody
	public AjaxResult partyMemberRecommendSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.PARTYMEMBER_RECOMMEND);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setPartymemberRecommend("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	
	/**
	 * 保存群团组织推优登记表
	 * @param file
	 * @param model
	 * @param user
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/groupRecommend/save")
	@ResponseBody
	public AjaxResult groupRecommendSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.GROUP_RECOMMEND);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setGroupRecommend("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	
	/**
	 * 保存积极分子备案登记表
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/activistRecords/save")
	@ResponseBody
	public AjaxResult activistRecordsSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.ACTIVIST_RECORDS);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setActivistRecords("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	
	/**
	 * 保存积极分子备案报告
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/activistRecordsReport/save")
	@ResponseBody
	public AjaxResult activistRecordsReportSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.ACTIVIST_RECORDS_REPORT);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setActivistRecordsReport("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	
	/**
	 * 保存积极分子培养考察登记表
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/activistCultivate/save")
	@ResponseBody
	public AjaxResult activistCultivateSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.ACTIVIST_CULTIVATE);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setActivistCultivate("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	
	/**
	 * 保存发展对象人选备案登记表
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/developmentRecords/save")
	@ResponseBody
	public AjaxResult developmentRecordsSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.DEVELOPMENT_RECORDS);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setDevelopmentRecords("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	
	/**
	 * 保存发展对象人选公示情况登记表
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/developmentPublicity/save")
	@ResponseBody
	public AjaxResult developmentPublicitySave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.DEVELOPMENT_PUBLICITY);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setDevelopmentPublicity("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	
	/**
	 * 保存发展对象备案报告
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/developmentRecordsReport/save")
	@ResponseBody
	public AjaxResult developmentRecordsReportSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.DEVELOPMENT_RECORDS_REPORT);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setDevelopmentRecordsReport("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	
	/**
	 * 保存发展对象短期集中培训情况登记表
	 */
	@RequiresPermissions("module:proposer:edit")
	@PostMapping("/developmentCultivate/save")
	@ResponseBody
	public AjaxResult developmentCultivateSave(MultipartFile file, Model model, User user) throws IllegalStateException, IOException{
        User users = ShiroUtils.getUser();
        boolean success = upload(user, file, Constants.DEVELOPMENT_CULTIVATE);
        if(success){
            Proposer proposer = proposerService.selectProposerById(user.getUserId());
            proposer.setDevelopmentCultivate("/"+user.getUserId()+"/"+file.getOriginalFilename());
            proposer.setUpdateBy(users.getUserName());
            proposer.setUpdateTime(new Date());
            proposerService.updateProposer(proposer);
            return success("上传成功");
        }
		return error("上传失败");
	}
	
	/**
	 * 查询申请人材料列表
	 */
	@RequiresPermissions("module:proposer:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Proposer proposer)
	{
		startPage();
        List<Proposer> list = proposerService.selectProposerList(proposer);
		return getDataTable(list);
	}
	
	/**
	 * 新增申请人材料
	 */
	@RequiresPermissions("module:proposer:add")
	@Log(title = "申请人材料", action = BusinessType.INSERT)
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}

	/**
	 * 修改申请人材料
	 */
	@RequiresPermissions("module:proposer:edit")
	@Log(title = "申请人材料", action = BusinessType.UPDATE)
	@GetMapping("/edit/{userId}")
	public String edit(@PathVariable("userId") Long userId, Model model)
	{
		Proposer proposer = proposerService.selectProposerById(userId);
		model.addAttribute("proposer", proposer);
	    return prefix + "/edit";
	}
	
	/**
	 * 保存申请人材料
	 */
	@RequiresPermissions("module:proposer:save")
	@Log(title = "申请人材料", action = BusinessType.SAVE)
	@PostMapping("/save")
	@ResponseBody
	public AjaxResult save(Proposer proposer)
	{
		System.out.println(proposer);
		if (proposerService.saveProposer(proposer) > 0)
		{
			return success();
		}
		return error();
	}
	
	/**
	 * 删除申请人材料
	 */
	@RequiresPermissions("module:proposer:remove")
	@Log(title = "申请人材料", action = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		int rows = proposerService.deleteProposerByIds(ids);
		if (rows > 0)
        {
            return success();
        }
        return error();
	}
	
	/**
	 * 文件预览
	 * @param fileName
	 * @param filePath
	 * @param response
	 * @throws IOException
	 */
	public void review(String fileName, String filePath, HttpServletResponse response) throws IOException{
        if(!"".equals(filePath)) {
            /*1)根据项目所在的服务器环境,确定路径中的 /  和 \ */
            String osName = System.getProperty("os.name");
            if (Pattern.matches("Linux.*", osName)) {
                filePath = "/" + filePath.replace("\\","/");
            } else if(Pattern.matches("Windows.*", osName)) {
                filePath.replace("/","\\");
            }

            /*2)获得文件名后缀*/
            String ext = "";
            if(!"".equals(fileName) && fileName.contains(".")){
                ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toUpperCase();
            }
            
            /*3)根据文件类型不同进行预览*/
            /*预览图片*/
            if ("PNG".equals(ext) || "JPEG".equals(ext) || "JPG".equals(ext)) {
                response.setContentType("image/jpeg");
            }
            /*预览BMP格式的文件*/
            if ("BMP".equals(ext)) {
                response.setContentType("image/bmp");
            }
            /*预览pdf*/
            if ("PDF".equals(ext)) {
                response.setContentType("application/pdf");
            }

            /*利用openOffice将office文件转换为pdf格式, 然后预览doc, docx, xls, xlsx, ppt, pptx */
            if ("DOC".equals(ext) || "DOCX".equals(ext) || "XLS".equals(ext) || "XLSX".equals(ext) || "PPT".equals(ext) || "PPTX".equals(ext)) {
                File docFile = new File(filePath);
                /*转换之后的文件名*/
                File pdfFile;
                if(filePath.contains(".")){
                    pdfFile = new File(filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf");
                }else{
                    pdfFile = new File(filePath + ".pdf");
                }

                /*判断即将要转换的文件是否真实存在*/
                if (docFile.exists()) {
                    /*判断改文件是否已经被转换过,若已经转换则直接预览*/
                    if (!pdfFile.exists()) {
                        try {
                        	System.out.println(docFile+" "+pdfFile);
                        	documentConverter.convert(docFile).to(pdfFile).execute();
                            filePath = pdfFile.getPath(); //文件转换之后的路径
                            response.setContentType("application/pdf");
                        } catch (Exception e) {
                            e.printStackTrace();  
                        }finally { //发生exception时, connection不会自动切断, 程序会一直挂着
                        	//TODO
                        }
                    } else {
                        filePath = pdfFile.getPath(); //文件已经转换过
                        response.setContentType("application/pdf");
                    }
                } else {
                    System.err.println("需要预览的文档在服务器中不存在!");
                }
            }
        }
	    FileInputStream fis = new FileInputStream(filePath);
	    OutputStream os = response.getOutputStream();
	    try {
	        int count = 0;
	        byte[] buffer = new byte[1024 * 1024];
	        while ((count = fis.read(buffer)) != -1)
	            os.write(buffer, 0, count);
	        os.flush();
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (os != null)
	            os.close();
	        if (fis != null)
	            fis.close();
	    }
	}
	
	/**
	 * 文件上传
	 */
	public boolean upload(User user, MultipartFile file, String type){
		boolean success = false;
		try {
			File document = null;
			String fileName = file.getOriginalFilename();  
			File firstFolder = new File(type);
			File secondFolder = new File(firstFolder + "/" + user.getUserId());
			if(!firstFolder.exists()){
				firstFolder.mkdirs();
			}
			if(!secondFolder.exists()){
				secondFolder.mkdirs();
			}
			document = new File(secondFolder+"/",fileName);
			System.out.println("文件上传路径"+ document);
	        file.transferTo(document); 
	        success = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return success;
	}

}
